import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/product_userpostratio_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/product_userpostratio.dart';
import 'package:flutter_admin/pages/odoo/product_userpostratio/product_userpostratio_edit.dart';
import 'package:flutter_admin/pages/odoo/product_userpostratio/product_userpostratio_dialog.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/utils.dart';

class ProductUserpostratioList extends StatefulWidget {
  ProductUserpostratioList({Key? key}) : super(key: key);

  @override
  _ProductUserpostratioListState createState() =>
      _ProductUserpostratioListState();
}

class _ProductUserpostratioListState extends State<ProductUserpostratioList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  ProductUserpostratio productUserpostratio = ProductUserpostratio();
  List<ProductUserpostratio> selectedList = [];
  //工厂
  List<SelectOptionVO> factoryList = [];

  //车间
  List<SelectOptionVO> workshopList = [];

  //工位
  List<SelectOptionVO> stationList = [];
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    factoryList = await DynamicDataApi.getModelSelect(
        model: "hr.department",
        name: "complete_name",
        key: "parent_id",
        operator: "=",
        val: null);
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelect(
            width: 280,
            label: '生产工厂',
            dataList: factoryList,
            value: productUserpostratio.factoryId,
            onSaved: (v) {
              productUserpostratio.factoryId = v;
            },
            onChange: (v) async {
              if (productUserpostratio.factoryId != v) {
                formKey.currentState!.save();
                productUserpostratio.factoryId = v;
                productUserpostratio.workshopId = null;
                productUserpostratio.stationId = null;
                stationList = [];
                try {
                  workshopList = await DynamicDataApi.getModelSelect(
                      model: "hr.department",
                      name: "complete_name",
                      key: "parent_id",
                      operator: "=",
                      val: int.parse(v));
                } catch (e) {
                  workshopList = [];
                }
                setState(() {});
              }
            },
          ),
          CrySelect(
            width: 280,
            label: '生产车间',
            dataList: workshopList,
            value: productUserpostratio.workshopId,
            onSaved: (v) {
              productUserpostratio.workshopId = v;
            },
            onChange: (v) async {
              if (productUserpostratio.workshopId != v) {
                formKey.currentState!.save();
                productUserpostratio.workshopId = v;
                productUserpostratio.stationId = null;
                try {
                  stationList = await DynamicDataApi.getModelSelect(
                      model: "base.productionstation",
                      name: "stationname",
                      key: 'workshop_id',
                      val: int.parse(v));
                } catch (e) {
                  stationList = [];
                }
                setState(() {});
              }
            },
          ),
          CrySelect(
            width: 280,
            label: '设备工位',
            dataList: stationList,
            value: productUserpostratio.stationId,
            onSaved: (v) {
              productUserpostratio.stationId = v;
            },
          ),
          CryInput(
            width: 280,
            label: '岗位名称',
            value: productUserpostratio.postName,
            onSaved: (v) {
              productUserpostratio.postName = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        //isDisplayDesktop(context)?DataColumn(
        //  label: Text(S.of(context).operating),
        //):DataColumn(label: Container()),
        DataColumn(
          label: Text('车间名称'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('工厂名称'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('设备工位'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('岗位名称'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('岗位系数'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('备注'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('创建人'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('创建日期'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
      ],
      getCells: (m) {
        ProductUserpostratio productUserpostratio =
            ProductUserpostratio.fromMap(m);
        return [
          //isDisplayDesktop(context)?DataCell(
          //  CryButtonBar(
          //    children: [
          //      CryButton(
          //          iconData: Icons.edit,
          //          tip: S.of(context).modify,
          //          onPressed: () => _edit(productUserpostratio)),
          //    ],
          //  ),
          // ):DataCell(Container()),
          DataCell(Text(productUserpostratio.workshopName ?? '--')),
          DataCell(Text(productUserpostratio.factoryName ?? '--')),
          DataCell(Text(productUserpostratio.stationName ?? '--')),
          DataCell(Text(productUserpostratio.postName ?? '--')),
          DataCell(Text((productUserpostratio.postratio != null)
              ? productUserpostratio.postratio.toString()
              : '--')),
          DataCell(Text(productUserpostratio.remark ?? '--')),
          DataCell(Text(productUserpostratio.createUidName ?? '--')),
          DataCell(Text(productUserpostratio.createDate ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButtons.add(context, () => _edit(null)),
        CryButtons.edit(context,
            selectedList.length != 1 ? null : () => _edit(selectedList[0])),
        CryButtons.delete(context,
            selectedList.length < 1 ? null : () => _delete(selectedList)),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _edit(ProductUserpostratio? productUserpostratio) async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ProductUserpostratioEdit(
          productUserpostratio: productUserpostratio,
        ),
      ),
    ).then((v) {
      if (v != null) {
        if(productUserpostratio == null){
          // 新增时回到第一页
          tableKey.currentState?.pageTo(0);
        }
        _loadData();
      }
    });
  }

  _reset() {
    stationList = [];
    workshopList = [];
    productUserpostratio = ProductUserpostratio();
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await ProductUserpostratioOdooApi.page(
        data: {
          "page": page,
          "domainList": productUserpostratio.toDomainList()
        });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _delete(List<ProductUserpostratio> selectedList) async {
    cryConfirm(context, S.of(context).confirmDelete, (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      var result = await ProductUserpostratioOdooApi.removeByIds(ids);
      if (result.success!) {
        _query();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  _sort(column, {ascending}) {
    page.orders[0].column = column;
    page.orders[0].asc = ascending ?? !page.orders[0].asc!;
    _query();
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ProductUserpostratioDialog(),
      ),
    ).then((v) {
      if (v != null) {
        productUserpostratio = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<ProductUserpostratio>((e) => ProductUserpostratio.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.add) {
          _edit(null);
        } else if (v == OperationType.edit) {
          _edit(selectedList[0]);
        } else if (v == OperationType.delete) {
          _delete(selectedList);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          child: ListTile(
            leading: const Icon(Icons.add),
            title: Text('添加'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1,
            title: Text('修改'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length != 0,
          child: ListTile(
            leading: const Icon(Icons.delete), //Icons.delete
            enabled: selectedList.length != 0,
            title: Text('删除'),
          ),
        ),
      ],
    );
  }
}
